use std::{env::args, error::Error, fs::File, io::Write};

use lalrpop_util::lalrpop_mod;

mod ast;
mod ir;

lalrpop_mod!(sysy);

fn main() -> Result<(), Box<dyn Error>> {
    // 解析命令行参数
    let mut args = args();
    args.next();
    let mode = args.next().unwrap();

    assert_eq!(mode, "-koopa".to_string());

    let input = args.next().unwrap();
    args.next();
    let output = args.next().unwrap();

    let input = std::fs::read_to_string(input)?;

    let ast = sysy::CompUnitParser::new().parse(&input).unwrap();

    // println!("{:#?}", ast);

    let koopa_ir = ir::to_koopa(&ast)?;

    // println!("{}", koopa_ir);

    save_to_file(&output, &koopa_ir)?;

    Ok(())
}

fn save_to_file(file: &String, content: &String) -> Result<(), Box<dyn Error>> {
    let mut ofile = File::create(file)?;
    ofile.write(content.as_bytes())?;
    Ok(())
}
